home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 2 / Apprentice-Release2.iso / Tools / Languages / Harvest C 1.3 / Application / Examples / SC.001.Sample / Sample.c next >
Encoding:
C/C++ Source or Header  |  1989-06-01  |  30.3 KB  |  884 lines  |  [TEXT/MPS ]

  1. /*------------------------------------------------------------------------------
  2. #
  3. #    Apple Macintosh Developer Technical Support
  4. #
  5. #    MultiFinder-Aware Simple Sample Application
  6. #
  7. #    Sample
  8. #
  9. #    Sample.c    -    C Source
  10. #
  11. #    Copyright © 1989 Apple Computer, Inc.
  12. #    All rights reserved.
  13. #
  14. #    Versions:    
  15. #                1.00                08/88
  16. #                1.01                11/88
  17. #                1.02                04/89
  18. #                1.03                06/89
  19. #
  20. #    Components:
  21. #                Sample.p            June 1, 1989
  22. #                Sample.c            June 1, 1989
  23. #                Sample.a            June 1, 1989
  24. #                Sample.inc1.a        June 1, 1989
  25. #                SampleMisc.a        June 1, 1989
  26. #                Sample.r            June 1, 1989
  27. #                Sample.h            June 1, 1989
  28. #                PSample.make        June 1, 1989
  29. #                CSample.make        June 1, 1989
  30. #                ASample.make        June 1, 1989
  31. #
  32. #    Sample is an example application that demonstrates how to
  33. #    initialize the commonly used toolbox managers, operate 
  34. #    successfully under MultiFinder, handle desk accessories, 
  35. #    and create, grow, and zoom windows.
  36. #
  37. #    It does not by any means demonstrate all the techniques 
  38. #    you need for a large application. In particular, Sample 
  39. #    does not cover exception handling, multiple windows/documents, 
  40. #    sophisticated memory management, printing, or undo. All of 
  41. #    these are vital parts of a normal full-sized application.
  42. #
  43. #    This application is an example of the form of a Macintosh 
  44. #    application; it is NOT a template. It is NOT intended to be 
  45. #    used as a foundation for the next world-class, best-selling, 
  46. #    600K application. A stick figure drawing of the human body may 
  47. #    be a good example of the form for a painting, but that does not 
  48. #    mean it should be used as the basis for the next Mona Lisa.
  49. #
  50. #    We recommend that you review this program or TESample before 
  51. #    beginning a new application.
  52. #
  53. ------------------------------------------------------------------------------*/
  54.  
  55.  
  56. /* Segmentation strategy:
  57.  
  58.    This program consists of three segments. Main contains most of the code,
  59.    including the MPW libraries, and the main program. Initialize contains
  60.    code that is only used once, during startup, and can be unloaded after the
  61.    program starts. %A5Init is automatically created by the Linker to initialize
  62.    globals for the MPW libraries and is unloaded right away. */
  63.  
  64.  
  65. /* SetPort strategy:
  66.  
  67.    Toolbox routines do not change the current port. In spite of this, in this
  68.    program we use a strategy of calling SetPort whenever we want to draw or
  69.    make calls which depend on the current port. This makes us less vulnerable
  70.    to bugs in other software which might alter the current port (such as the
  71.    bug (feature?) in many desk accessories which change the port on OpenDeskAcc).
  72.    Hopefully, this also makes the routines from this program more self-contained,
  73.    since they don't depend on the current port setting. */
  74.  
  75.  
  76. #include <Values.h>
  77. #include <Types.h>
  78. #include <Resources.h>
  79. #include <QuickDraw.h>
  80. #include <Fonts.h>
  81. #include <Events.h>
  82. #include <Windows.h>
  83. #include <Menus.h>
  84. #include <TextEdit.h>
  85. #include <Dialogs.h>
  86. #include <Desk.h>
  87. #include <ToolUtils.h>
  88. #include <Memory.h>
  89. #include <SegLoad.h>
  90. #include <Files.h>
  91. #include <OSUtils.h>
  92. #include <OSEvents.h>
  93. #include <DiskInit.h>
  94. #include <Packages.h>
  95. #include <Traps.h>
  96. #include <Sample.h>        /* bring in all the #defines for Sample */
  97.  
  98.  
  99. /* The "g" prefix is used to emphasize that a variable is global. */
  100.  
  101. /* GMac is used to hold the result of a SysEnvirons call. This makes
  102.    it convenient for any routine to check the environment. */
  103. SysEnvRec    gMac;                /* set up by Initialize */
  104.  
  105. /* GHasWaitNextEvent is set at startup, and tells whether the WaitNextEvent
  106.    trap is available. If it is false, we know that we must call GetNextEvent. */
  107. Boolean        gHasWaitNextEvent;    /* set up by Initialize */
  108.  
  109. /* GInBackground is maintained by our osEvent handling routines. Any part of
  110.    the program can check it to find out if it is currently in the background. */
  111. Boolean        gInBackground;        /* maintained by Initialize and DoEvent */
  112.  
  113.  
  114. /* The following globals are the state of the window. If we supported more than
  115.    one window, they would be attatched to each document, rather than globals. */
  116.  
  117. /* GStopped tells whether the stop light is currently on stop or go. */
  118. Boolean        gStopped;            /* maintained by Initialize and SetLight */
  119.  
  120. /* GStopRect and gGoRect are the rectangles of the two stop lights in the window. */
  121. Rect        gStopRect;            /* set up by Initialize */
  122. Rect        gGoRect;            /* set up by Initialize */
  123.  
  124.  
  125. /* Here are declarations for all of the C routines. In MPW 3.0 we can use
  126.    actual prototypes for parameter type checking. */
  127. void EventLoop( void );
  128. void DoEvent( EventRecord *event );
  129. void AdjustCursor( Point mouse, RgnHandle region );
  130. void GetGlobalMouse( Point *mouse );
  131. void DoUpdate( WindowPtr window );
  132. void DoActivate( WindowPtr window, Boolean becomingActive );
  133. void DoContentClick( WindowPtr window );
  134. void DrawWindow( WindowPtr window );
  135. void AdjustMenus( void );
  136. void DoMenuCommand( long menuResult );
  137. void SetLight( WindowPtr window, Boolean newStopped );
  138. Boolean DoCloseWindow( WindowPtr window );
  139. void Terminate( void );
  140. void Initialize( void );
  141. Boolean GoGetRect( short rectID, Rect *theRect );
  142. void ForceEnvirons( void );
  143. Boolean IsAppWindow( WindowPtr window );
  144. Boolean IsDAWindow( WindowPtr window );
  145. Boolean TrapAvailable( short tNumber, TrapType tType );
  146. void AlertUser( void );
  147.  
  148.  
  149. /* Define HiWrd and LoWrd macros for efficiency. */
  150. #define HiWrd(aLong)    (((aLong) >> 16) & 0xFFFF)
  151. #define LoWrd(aLong)    ((aLong) & 0xFFFF)
  152.  
  153. /* Define TopLeft and BotRight macros for convenience. Notice the implicit
  154.    dependency on the ordering of fields within a Rect */
  155. #define TopLeft(aRect)    (* (Point *) &(aRect).top)
  156. #define BotRight(aRect)    (* (Point *) &(aRect).bottom)
  157.  
  158.  
  159. extern void _DataInit();
  160.  
  161. /* This routine is part of the MPW runtime library. This external
  162.    reference to it is done so that we can unload its segment, %A5Init. */
  163.  
  164.  
  165. #pragma segment Main
  166. main()
  167. {
  168.     UnloadSeg((Ptr) _DataInit);        /* note that _DataInit must not be in Main! */
  169.     
  170.     /* 1.01 - call to ForceEnvirons removed */
  171.     
  172.     /*    If you have stack requirements that differ from the default,
  173.         then you could use SetApplLimit to increase StackSpace at 
  174.         this point, before calling MaxApplZone. */
  175.     MaxApplZone();                    /* expand the heap so code segments load at the top */
  176.  
  177.     Initialize();                    /* initialize the program */
  178.     UnloadSeg((Ptr) Initialize);    /* note that Initialize must not be in Main! */
  179.  
  180.     EventLoop();                    /* call the main event loop */
  181. }
  182.  
  183.  
  184. /*    Get events forever, and handle them by calling DoEvent.
  185.     Get the events by calling WaitNextEvent, if it's available, otherwise
  186.     by calling GetNextEvent. Also call AdjustCursor each time through the loop. */
  187.  
  188. #pragma segment Main
  189. void EventLoop()
  190. {
  191.     RgnHandle    cursorRgn;
  192.     Boolean        gotEvent;
  193.     EventRecord    event;
  194.     Point        mouse;
  195.  
  196.     cursorRgn = NewRgn();            /* we’ll pass WNE an empty region the 1st time thru */
  197.     do {
  198.         /* use WNE if it is available */
  199.         if ( gHasWaitNextEvent ) {
  200.             GetGlobalMouse(&mouse);
  201.             AdjustCursor(mouse, cursorRgn);
  202.             gotEvent = WaitNextEvent(everyEvent, &event, MAXLONG, cursorRgn);
  203.         }
  204.         else {
  205.             SystemTask();
  206.             gotEvent = GetNextEvent(everyEvent, &event);
  207.         }
  208.         if ( gotEvent ) {
  209.             /* make sure we have the right cursor before handling the event */
  210.             AdjustCursor(event.where, cursorRgn);
  211.             DoEvent(&event);
  212.         }
  213.         /*    If you are using modeless dialogs that have editText items,
  214.             you will want to call IsDialogEvent to give the caret a chance
  215.             to blink, even if WNE/GNE returned FALSE. However, check FrontWindow
  216.             for a non-NIL value before calling IsDialogEvent. */
  217.     } while ( true );    /* loop forever; we quit via ExitToShell */
  218. } /*EventLoop*/
  219.  
  220.  
  221. /* Do the right thing for an event. Determine what kind of event it is, and call
  222.  the appropriate routines. */
  223.  
  224. #pragma segment Main
  225. void DoEvent(event)
  226.     EventRecord    *event;
  227. {
  228.     short        part, err;
  229.     WindowPtr    window;
  230.     Boolean        hit;
  231.     char        key;
  232.     Point        aPoint;
  233.  
  234.     switch ( event->what ) {
  235.         case mouseDown:
  236.             part = FindWindow(event->where, &window);
  237.             switch ( part ) {
  238.                 case inMenuBar:                /* process a mouse menu command (if any) */
  239.                     AdjustMenus();
  240.                     DoMenuCommand(MenuSelect(event->where));
  241.                     break;
  242.                 case inSysWindow:            /* let the system handle the mouseDown */
  243.                     SystemClick(event, window);
  244.                     break;
  245.                 case inContent:
  246.                     if ( window != FrontWindow() ) {
  247.                         SelectWindow(window);
  248.                         /*DoEvent(event);*/    /* use this line for "do first click" */
  249.                     } else
  250.                         DoContentClick(window);
  251.                     break;
  252.                 case inDrag:                /* pass screenBits.bounds to get all gDevices */
  253.                     DragWindow(window, event->where, &qd.screenBits.bounds);
  254.                     break;
  255.                 case inGrow:
  256.                     break;
  257.                 case inZoomIn:
  258.                 case inZoomOut:
  259.                     hit = TrackBox(window, event->where, part);
  260.                     if ( hit ) {
  261.                         SetPort(window);                /* the window must be the current port... */
  262.                         EraseRect(&window->portRect);    /* because of a bug in ZoomWindow */
  263.                         ZoomWindow(window, part, true);    /* note that we invalidate and erase... */
  264.                         InvalRect(&window->portRect);    /* to make things look better on-screen */
  265.                     }
  266.                     break;
  267.             }
  268.             break;
  269.         case keyDown:
  270.         case autoKey:                        /* check for menukey equivalents */
  271.             key = event->message & charCodeMask;
  272.             if ( event->modifiers & cmdKey )            /* Command key down */
  273.                 if ( event->what == keyDown ) {
  274.                     AdjustMenus();                        /* enable/disable/check menu items properly */
  275.                     DoMenuCommand(MenuKey(key));
  276.                 }
  277.             break;
  278.         case activateEvt:
  279.             DoActivate((WindowPtr) event->message, (event->modifiers & activeFlag) != 0);
  280.             break;
  281.         case updateEvt:
  282.             DoUpdate((WindowPtr) event->message);
  283.             break;
  284.         /*    1.01 - It is not a bad idea to at least call DIBadMount in response
  285.             to a diskEvt, so that the user can format a floppy. */
  286.         case diskEvt:
  287.             if ( HiWord(event->message) != noErr ) {
  288.                 SetPt(&aPoint, kDILeft, kDITop);
  289.                 err = DIBadMount(aPoint, event->message);
  290.             }
  291.             break;
  292.         case kOSEvent:
  293.         /*    1.02 - must BitAND with 0x0FF to get only low byte */
  294.             switch ((event->message >> 24) & 0x0FF) {        /* high byte of message */
  295.                 case kSuspendResumeMessage:        /* suspend/resume is also an activate/deactivate */
  296.                     gInBackground = (event->message & kResumeMask) == 0;
  297.                     DoActivate(FrontWindow(), !gInBackground);
  298.                     break;
  299.             }
  300.             break;
  301.     }
  302. } /*DoEvent*/
  303.  
  304.  
  305. /*    Change the cursor's shape, depending on its position. This also calculates the region
  306.     where the current cursor resides (for WaitNextEvent). If the mouse is ever outside of
  307.     that region, an event would be generated, causing this routine to be called,
  308.     allowing us to change the region to the region the mouse is currently in. If
  309.     there is more to the event than just “the mouse moved”, we get called before the
  310.     event is processed to make sure the cursor is the right one. In any (ahem) event,
  311.     this is called again before we     fall back into WNE. */
  312.  
  313. #pragma segment Main
  314. void AdjustCursor(mouse,region)
  315.     Point        mouse;
  316.     RgnHandle    region;
  317. {
  318.     WindowPtr    window;
  319.     RgnHandle    arrowRgn;
  320.     RgnHandle    plusRgn;
  321.     Rect        globalPortRect;
  322.  
  323.     window = FrontWindow();    /* we only adjust the cursor when we are in front */
  324.     if ( (! gInBackground) && (! IsDAWindow(window)) ) {
  325.         /* calculate regions for different cursor shapes */
  326.         arrowRgn = NewRgn();
  327.         plusRgn = NewRgn();
  328.  
  329.         /* start with a big, big rectangular region */
  330.         SetRectRgn(arrowRgn, kExtremeNeg, kExtremeNeg, kExtremePos, kExtremePos);
  331.  
  332.         /* calculate plusRgn */
  333.         if ( IsAppWindow(window) ) {
  334.             SetPort(window);    /* make a global version of the viewRect */
  335.             SetOrigin(-window->portBits.bounds.left, -window->portBits.bounds.top);
  336.             globalPortRect = window->portRect;
  337.             RectRgn(plusRgn, &globalPortRect);
  338.             SectRgn(plusRgn, window->visRgn, plusRgn);
  339.             SetOrigin(0, 0);
  340.         }
  341.  
  342.         /* subtract other regions from arrowRgn */
  343.         DiffRgn(arrowRgn, plusRgn, arrowRgn);
  344.  
  345.         /* change the cursor and the region parameter */
  346.         if ( PtInRgn(mouse, plusRgn) ) {
  347.             SetCursor(*GetCursor(plusCursor));
  348.             CopyRgn(plusRgn, region);
  349.         } else {
  350.             SetCursor(&qd.arrow);
  351.             CopyRgn(arrowRgn, region);
  352.         }
  353.  
  354.         /* get rid of our local regions */
  355.         DisposeRgn(arrowRgn);
  356.         DisposeRgn(plusRgn);
  357.     }
  358. } /*AdjustCursor*/
  359.  
  360.  
  361. /*    Get the global coordinates of the mouse. When you call OSEventAvail
  362.     it will return either a pending event or a null event. In either case,
  363.     the where field of the event record will contain the current position
  364.     of the mouse in global coordinates and the modifiers field will reflect
  365.     the current state of the modifiers. Another way to get the global
  366.     coordinates is to call GetMouse and LocalToGlobal, but that requires
  367.     being sure that thePort is set to a valid port. */
  368.  
  369. #pragma segment Main
  370. void GetGlobalMouse(mouse)
  371.     Point    *mouse;
  372. {
  373.     EventRecord    event;
  374.     
  375.     OSEventAvail(kNoEvents, &event);    /* we aren't interested in any events */
  376.     *mouse = event.where;                /* just the mouse position */
  377. } /*GetGlobalMouse*/
  378.  
  379.  
  380. /*    This is called when an update event is received for a window.
  381.     It calls DrawWindow to draw the contents of an application window.
  382.     As an effeciency measure that does not have to be followed, it
  383.     calls the drawing routine only if the visRgn is non-empty. This
  384.     will handle situations where calculations for drawing or drawing
  385.     itself is very time-consuming. */
  386.  
  387. #pragma segment Main
  388. void DoUpdate(window)
  389.     WindowPtr    window;
  390. {
  391.     if ( IsAppWindow(window) ) {
  392.         BeginUpdate(window);                /* this sets up the visRgn */
  393.         if ( ! EmptyRgn(window->visRgn) )    /* draw if updating needs to be done */
  394.             DrawWindow(window);
  395.         EndUpdate(window);
  396.     }
  397. } /*DoUpdate*/
  398.  
  399.  
  400. /*    This is called when a window is activated or deactivated.
  401.     In Sample, the Window Manager's handling of activate and
  402.     deactivate events is sufficient. Other applications may have
  403.     TextEdit records, controls, lists, etc., to activate/deactivate. */
  404.  
  405. #pragma segment Main
  406. void DoActivate(window, becomingActive)
  407.     WindowPtr    window;
  408.     Boolean        becomingActive;
  409. {
  410.     if ( IsAppWindow(window) ) {
  411.         if ( becomingActive )
  412.             /* do whatever you need to at activation */ ;
  413.         else
  414.             /* do whatever you need to at deactivation */ ;
  415.     }
  416. } /*DoActivate*/
  417.  
  418.  
  419. /*    This is called when a mouse-down event occurs in the content of a window.
  420.     Other applications might want to call FindControl, TEClick, etc., to
  421.     further process the click. */
  422.  
  423. #pragma segment Main
  424. void DoContentClick(window)
  425.     WindowPtr    window;
  426. {
  427.     SetLight(window, ! gStopped);
  428. } /*DoContentClick*/
  429.  
  430.  
  431. /* Draw the contents of the application window. We do some drawing in color, using
  432.    Classic QuickDraw's color capabilities. This will be black and white on old
  433.    machines, but color on color machines. At this point, the window’s visRgn
  434.    is set to allow drawing only where it needs to be done. */
  435.  
  436. #pragma segment Main
  437. void DrawWindow(window)
  438.     WindowPtr    window;
  439. {
  440.     SetPort(window);
  441.  
  442.     EraseRect(&window->portRect);    /* clear out any garbage that may linger */
  443.     if ( gStopped )                    /* draw a red (or white) stop light */
  444.         ForeColor(redColor);
  445.     else
  446.         ForeColor(whiteColor);
  447.     PaintOval(&gStopRect);
  448.     ForeColor(blackColor);
  449.     FrameOval(&gStopRect);
  450.     if ( ! gStopped )                /* draw a green (or white) go light */
  451.         ForeColor(greenColor);
  452.     else
  453.         ForeColor(whiteColor);
  454.     PaintOval(&gGoRect);
  455.     ForeColor(blackColor);
  456.     FrameOval(&gGoRect);
  457. } /*DrawWindow*/
  458.  
  459.  
  460. /*    Enable and disable menus based on the current state.
  461.     The user can only select enabled menu items. We set up all the menu items
  462.     before calling MenuSelect or MenuKey, since these are the only times that
  463.     a menu item can be selected. Note that MenuSelect is also the only time
  464.     the user will see menu items. This approach to deciding what enable/
  465.     disable state a menu item has the advantage of concentrating all
  466.     the decision-making in one routine, as opposed to being spread throughout
  467.     the application. Other application designs may take a different approach
  468.     that is just as valid. */
  469.  
  470. #pragma segment Main
  471. void AdjustMenus()
  472. {
  473.     WindowPtr    window;
  474.     MenuHandle    menu;
  475.  
  476.     window = FrontWindow();
  477.  
  478.     menu = GetMHandle(mFile);
  479.     if ( IsDAWindow(window) )        /* we can allow desk accessories to be closed from the menu */
  480.         EnableItem(menu, iClose);
  481.     else
  482.         DisableItem(menu, iClose);    /* but not our traffic light window */
  483.  
  484.     menu = GetMHandle(mEdit);
  485.     if ( IsDAWindow(window) ) {        /* a desk accessory might need the edit menu… */
  486.         EnableItem(menu, iUndo);
  487.         EnableItem(menu, iCut);
  488.         EnableItem(menu, iCopy);
  489.         EnableItem(menu, iClear);
  490.         EnableItem(menu, iPaste);
  491.     } else {                        /* …but we don’t use it */
  492.         DisableItem(menu, iUndo);
  493.         DisableItem(menu, iCut);
  494.         DisableItem(menu, iCopy);
  495.         DisableItem(menu, iClear);
  496.         DisableItem(menu, iPaste);
  497.     }
  498.  
  499.     menu = GetMHandle(mLight);
  500.     if ( IsAppWindow(window) ) {    /* we know that it must be the traffic light */
  501.         EnableItem(menu, iStop);
  502.         EnableItem(menu, iGo);
  503.     } else {
  504.         DisableItem(menu, iStop);
  505.         DisableItem(menu, iGo);
  506.     }
  507.     CheckItem(menu, iStop, gStopped); /* we can also determine check/uncheck state, too */
  508.     CheckItem(menu, iGo, ! gStopped);
  509. } /*AdjustMenus*/
  510.  
  511.  
  512. /*    This is called when an item is chosen from the menu bar (after calling
  513.     MenuSelect or MenuKey). It performs the right operation for each command.
  514.     It is good to have both the result of MenuSelect and MenuKey go to
  515.     one routine like this to keep everything organized. */
  516.  
  517. #pragma segment Main
  518. void DoMenuCommand(menuResult)
  519.     long        menuResult;
  520. {
  521.     short        menuID;                /* the resource ID of the selected menu */
  522.     short        menuItem;            /* the item number of the selected menu */
  523.     short        itemHit;
  524.     Str255        daName;
  525.     short        daRefNum;
  526.     Boolean        handledByDA;
  527.  
  528.     menuID = HiWord(menuResult);    /* use macros for efficiency to... */
  529.     menuItem = LoWord(menuResult);    /* get menu item number and menu number */
  530.     switch ( menuID ) {
  531.         case mApple:
  532.             switch ( menuItem ) {
  533.                 case iAbout:        /* bring up alert for About */
  534.                     itemHit = Alert(rAboutAlert, nil);
  535.                     break;
  536.                 default:            /* all non-About items in this menu are DAs */
  537.                     /* type Str255 is an array in MPW 3 */
  538.                     GetItem(GetMHandle(mApple), menuItem, daName);
  539.                     daRefNum = OpenDeskAcc(daName);
  540.                     break;
  541.             }
  542.             break;
  543.         case mFile:
  544.             switch ( menuItem ) {
  545.                 case iClose:
  546.                     DoCloseWindow(FrontWindow());
  547.                     break;
  548.                 case iQuit:
  549.                     Terminate();
  550.                     break;
  551.             }
  552.             break;
  553.         case mEdit:                    /* call SystemEdit for DA editing & MultiFinder */
  554.             handledByDA = SystemEdit(menuItem-1);    /* since we don’t do any Editing */
  555.             break;
  556.         case mLight:
  557.             switch ( menuItem ) {
  558.                 case iStop:
  559.                     SetLight(FrontWindow(), true);
  560.                     break;
  561.                 case iGo:
  562.                     SetLight(FrontWindow(), false);
  563.                     break;
  564.             }
  565.             break;
  566.     }
  567.     HiliteMenu(0);                    /* unhighlight what MenuSelect (or MenuKey) hilited */
  568. } /*DoMenuCommand*/
  569.  
  570.  
  571. /* Change the setting of the light. */
  572.  
  573. #pragma segment Main
  574. void SetLight( window, newStopped )
  575.     WindowPtr    window;
  576.     Boolean        newStopped;
  577. {
  578.     if ( newStopped != gStopped ) {
  579.         gStopped = newStopped;
  580.         SetPort(window);
  581.         InvalRect(&window->portRect);
  582.     }
  583. } /*SetLight*/
  584.  
  585.  
  586. /* Close a window. This handles desk accessory and application windows. */
  587.  
  588. /*    1.01 - At this point, if there was a document associated with a
  589.     window, you could do any document saving processing if it is 'dirty'.
  590.     DoCloseWindow would return true if the window actually closed, i.e.,
  591.     the user didn’t cancel from a save dialog. This result is handy when
  592.     the user quits an application, but then cancels the save of a document
  593.     associated with a window. */
  594.  
  595. #pragma segment Main
  596. Boolean DoCloseWindow(window)
  597.     WindowPtr    window;
  598. {
  599.     if ( IsDAWindow(window) )
  600.         CloseDeskAcc(((WindowPeek) window)->windowKind);
  601.     else if ( IsAppWindow(window) )
  602.         CloseWindow(window);
  603.     return true;
  604. } /*DoCloseWindow*/
  605.  
  606.  
  607. /**************************************************************************************
  608. *** 1.01 DoCloseBehind(window) was removed ***
  609.  
  610.     1.01 - DoCloseBehind was a good idea for closing windows when quitting
  611.     and not having to worry about updating the windows, but it suffered
  612.     from a fatal flaw. If a desk accessory owned two windows, it would
  613.     close both those windows when CloseDeskAcc was called. When DoCloseBehind
  614.     got around to calling DoCloseWindow for that other window that was already
  615.     closed, things would go very poorly. Another option would be to have a
  616.     procedure, GetRearWindow, that would go through the window list and return
  617.     the last window. Instead, we decided to present the standard approach
  618.     of getting and closing FrontWindow until FrontWindow returns NIL. This
  619.     has a potential benefit in that the window whose document needs to be saved
  620.     may be visible since it is the front window, therefore decreasing the
  621.     chance of user confusion. For aesthetic reasons, the windows in the
  622.     application should be checked for updates periodically and have the
  623.     updates serviced.
  624. **************************************************************************************/
  625.  
  626.  
  627. /* Clean up the application and exit. We close all of the windows so that
  628.  they can update their documents, if any. */
  629.  
  630. /*    1.01 - If we find out that a cancel has occurred, we won't exit to the
  631.     shell, but will return instead. */
  632.  
  633. #pragma segment Main
  634. void Terminate()
  635. {
  636.     WindowPtr    aWindow;
  637.     Boolean        closed;
  638.     
  639.     closed = true;
  640.     do {
  641.         aWindow = FrontWindow();                /* get the current front window */
  642.         if (aWindow != nil)
  643.             closed = DoCloseWindow(aWindow);    /* close this window */    
  644.     }
  645.     while (closed && (aWindow != nil));
  646.     if (closed)
  647.         ExitToShell();                            /* exit if no cancellation */
  648. } /*Terminate*/
  649.  
  650.  
  651. /*    Set up the whole world, including global variables, Toolbox managers,
  652.     and menus. We also create our one application window at this time.
  653.     Since window storage is non-relocateable, how and when to allocate space
  654.     for windows is very important so that heap fragmentation does not occur.
  655.     Because Sample has only one window and it is only disposed when the application
  656.     quits, we will allocate its space here, before anything that might be a locked
  657.     relocatable object gets into the heap. This way, we can force the storage to be
  658.     in the lowest memory available in the heap. Window storage can differ widely
  659.     amongst applications depending on how many windows are created and disposed. */
  660.  
  661. /*    1.01 - The code that used to be part of ForceEnvirons has been moved into
  662.     this module. If an error is detected, instead of merely doing an ExitToShell,
  663.     which leaves the user without much to go on, we call AlertUser, which puts
  664.     up a simple alert that just says an error occurred and then calls ExitToShell.
  665.     Since there is no other cleanup needed at this point if an error is detected,
  666.     this form of error- handling is acceptable. If more sophisticated error recovery
  667.     is needed, an exception mechanism, such as is provided by Signals, can be used. */
  668.  
  669. #pragma segment Initialize
  670. void Initialize()
  671. {
  672.     Handle        menuBar;
  673.     WindowPtr    window;
  674.     long        total, contig;
  675.     EventRecord event;
  676.     short        count;
  677.  
  678.     gInBackground = false;
  679.  
  680.     InitGraf((Ptr) &qd.thePort);
  681.     InitFonts();
  682.     InitWindows();
  683.     InitMenus();
  684.     TEInit();
  685.     InitDialogs(nil);
  686.     InitCursor();
  687.     
  688.     /*    Call MPPOpen and ATPLoad at this point to initialize AppleTalk,
  689.          if you are using it. */
  690.     /*    NOTE -- It is no longer necessary, and actually unhealthy, to check
  691.         PortBUse and SPConfig before opening AppleTalk. The drivers are capable
  692.         of checking for port availability themselves. */
  693.     
  694.     /*    This next bit of code is necessary to allow the default button of our
  695.         alert be outlined.
  696.         1.02 - Changed to call EventAvail so that we don't lose some important
  697.         events. */
  698.      
  699.     for (count = 1; count <= 3; count++)
  700.         EventAvail(everyEvent, &event);
  701.     
  702.     /*    Ignore the error returned from SysEnvirons; even if an error occurred,
  703.         the SysEnvirons glue will fill in the SysEnvRec. You can save a redundant
  704.         call to SysEnvirons by calling it after initializing AppleTalk. */
  705.      
  706.     SysEnvirons(kSysEnvironsVersion, &gMac);
  707.     
  708.     /* Make sure that the machine has at least 128K ROMs. If it doesn't, exit. */
  709.     
  710.     if (gMac.machineType < 0) AlertUser();
  711.     
  712.     /*    1.02 - Move TrapAvailable call to after SysEnvirons so that we can tell
  713.         in TrapAvailable if a tool trap value is out of range. */
  714.         
  715.     gHasWaitNextEvent = TrapAvailable(_WaitNextEvent, ToolTrap);
  716.  
  717.     /*    1.01 - We used to make a check for memory at this point by examining ApplLimit,
  718.         ApplicZone, and StackSpace and comparing that to the minimum size we told
  719.         MultiFinder we needed. This did not work well because it assumed too much about
  720.         the relationship between what we asked MultiFinder for and what we would actually
  721.         get back, as well as how to measure it. Instead, we will use an alternate
  722.         method comprised of two steps. */
  723.      
  724.     /*    It is better to first check the size of the application heap against a value
  725.         that you have determined is the smallest heap the application can reasonably
  726.         work in. This number should be derived by examining the size of the heap that
  727.         is actually provided by MultiFinder when the minimum size requested is used.
  728.         The derivation of the minimum size requested from MultiFinder is described
  729.         in Sample.h. The check should be made because the preferred size can end up
  730.         being set smaller than the minimum size by the user. This extra check acts to
  731.         insure that your application is starting from a solid memory foundation. */
  732.      
  733.     if ((long) GetApplLimit() - (long) ApplicZone() < kMinHeap) AlertUser();
  734.     
  735.     /*    Next, make sure that enough memory is free for your application to run. It
  736.         is possible for a situation to arise where the heap may have been of required
  737.         size, but a large scrap was loaded which left too little memory. To check for
  738.         this, call PurgeSpace and compare the result with a value that you have determined
  739.         is the minimum amount of free memory your application needs at initialization.
  740.         This number can be derived several different ways. One way that is fairly
  741.         straightforward is to run the application in the minimum size configuration
  742.         as described previously. Call PurgeSpace at initialization and examine the value
  743.         returned. However, you should make sure that this result is not being modified
  744.         by the scrap's presence. You can do that by calling ZeroScrap before calling
  745.         PurgeSpace. Make sure to remove that call before shipping, though. */
  746.     
  747.     /* ZeroScrap(); */
  748.  
  749.     PurgeSpace(&total, &contig);
  750.     if (total < kMinSpace) AlertUser();
  751.  
  752.     /*    The extra benefit to waiting until after the Toolbox Managers have been initialized
  753.         to check memory is that we can now give the user an alert to tell him/her what
  754.         happened. Although it is possible that the memory situation could be worsened by
  755.         displaying an alert, MultiFinder would gracefully exit the application with
  756.         an informative alert if memory became critical. Here we are acting more
  757.         in a preventative manner to avoid future disaster from low-memory problems. */
  758.  
  759.     /*     we will allocate our own window storage instead of letting the Window
  760.         Manager do it because GetNewWindow may load in temp. resources before
  761.         making the NewPtr call, and this can lead to heap fragmentation. */
  762.     window = (WindowPtr) NewPtr(sizeof(WindowRecord));
  763.     if ( window == nil ) AlertUser();
  764.     window = GetNewWindow(rWindow, (Ptr) window, (WindowPtr) -1);
  765.  
  766.     menuBar = GetNewMBar(rMenuBar);            /* read menus into menu bar */
  767.     if ( menuBar == nil ) AlertUser();
  768.     SetMenuBar(menuBar);                    /* install menus */
  769.     DisposHandle(menuBar);
  770.     AddResMenu(GetMHandle(mApple), 'DRVR');    /* add DA names to Apple menu */
  771.     DrawMenuBar();
  772.     
  773.     gStopped = true;
  774.     if ( !GoGetRect(rStopRect, &gStopRect) )
  775.         AlertUser();                        /* the stop light rectangle */
  776.     if ( !GoGetRect(rGoRect, &gGoRect) )
  777.         AlertUser();                        /* the go light rectangle */
  778. } /*Initialize*/
  779.  
  780.  
  781. /*    This utility loads the global rectangles that are used by the window
  782.     drawing routines. It shows how the resource manager can be used to hold
  783.     values in a convenient manner. These values are then easily altered without
  784.     having to re-compile the source code. In this particular case, we know
  785.     that this routine is being called at initialization time. Therefore,
  786.     if a failure occurs here, we will assume that the application is in such
  787.     bad shape that we should just exit. Your error handling may differ, but
  788.     the check should still be made. */
  789.     
  790. #pragma segment Initialize
  791. Boolean GoGetRect(rectID,theRect)
  792.     short    rectID;
  793.     Rect    *theRect;
  794. {
  795.     Handle        resource;
  796.     
  797.     resource = GetResource('RECT', rectID);
  798.     if ( resource != nil ) {
  799.         *theRect = **((Rect**) resource);
  800.         return true;
  801.     }
  802.     else
  803.         return false;
  804. } /* GoGetRect */
  805.  
  806.  
  807. /*    Check to see if a window belongs to the application. If the window pointer
  808.     passed was NIL, then it could not be an application window. WindowKinds
  809.     that are negative belong to the system and windowKinds less than userKind
  810.     are reserved by Apple except for windowKinds equal to dialogKind, which
  811.     mean it is a dialog.
  812.     1.02 - In order to reduce the chance of accidentally treating some window
  813.     as an AppWindow that shouldn't be, we'll only return true if the windowkind
  814.     is userKind. If you add different kinds of windows to Sample you'll need
  815.     to change how this all works. */
  816.  
  817. #pragma segment Main
  818. Boolean IsAppWindow(window)
  819.     WindowPtr    window;
  820. {
  821.     short        windowKind;
  822.  
  823.     if ( window == nil )
  824.         return false;
  825.     else {    /* application windows have windowKinds = userKind (8) */
  826.         windowKind = ((WindowPeek) window)->windowKind;
  827.         return ( windowKind == userKind );
  828.     }
  829. } /*IsAppWindow*/
  830.  
  831.  
  832. /* Check to see if a window belongs to a desk accessory. */
  833.  
  834. #pragma segment Main
  835. Boolean IsDAWindow(window)
  836.     WindowPtr    window;
  837. {
  838.     if ( window == nil )
  839.         return false;
  840.     else    /* DA windows have negative windowKinds */
  841.         return ( ((WindowPeek) window)->windowKind < 0 );
  842. } /*IsDAWindow*/
  843.  
  844.  
  845. /*    Check to see if a given trap is implemented. This is only used by the
  846.     Initialize routine in this program, so we put it in the Initialize segment.
  847.     The recommended approach to see if a trap is implemented is to see if
  848.     the address of the trap routine is the same as the address of the
  849.     Unimplemented trap. */
  850. /*    1.02 - Needs to be called after call to SysEnvirons so that it can check
  851.     if a ToolTrap is out of range of a pre-MacII ROM. */
  852.  
  853. #pragma segment Initialize
  854. Boolean TrapAvailable(tNumber,tType)
  855.     short        tNumber;
  856.     TrapType    tType;
  857. {
  858.     if ( ( tType == ToolTrap ) &&
  859.         ( gMac.machineType > envMachUnknown ) &&
  860.         ( gMac.machineType < envMacII ) ) {        /* it's a 512KE, Plus, or SE */
  861.         tNumber = tNumber & 0x03FF;
  862.         if ( tNumber > 0x01FF )                    /* which means the tool traps */
  863.             tNumber = _Unimplemented;            /* only go to 0x01FF */
  864.     }
  865.     return NGetTrapAddress(tNumber, tType) != GetTrapAddress(_Unimplemented);
  866. } /*TrapAvailable*/
  867.  
  868.  
  869. /*    Display an alert that tells the user an error occurred, then exit the program.
  870.     This routine is used as an ultimate bail-out for serious errors that prohibit
  871.     the continuation of the application. Errors that do not require the termination
  872.     of the application should be handled in a different manner. Error checking and
  873.     reporting has a place even in the simplest application. The error number is used
  874.     to index an 'STR#' resource so that a relevant message can be displayed. */
  875.  
  876. #pragma segment Main
  877. void AlertUser()
  878. {
  879.     short        itemHit;
  880.  
  881.     SetCursor(&qd.arrow);
  882.     itemHit = Alert(rUserAlert, nil);
  883.     ExitToShell();
  884. } /* AlertUser */